<?php
/**
 * Created by PhpStorm.
 * User: surestdeng
 * Date: 2019/12/24
 * Time: 14:10:59
 */

namespace App\Repositories\Handler;


use App\Models\Article;
use App\Models\Platform;
use App\Models\TagRelation;
use Illuminate\Support\Arr;

class LearnkuHandler implements HandlerInterface
{
    protected $key = ':article';
    /**
     * 数据处理
     * User: surest
     * Date: 2019/12/24
     * @param $data
     */
    public function handle(array $data, string $platform) :array
    {
        $data = $this->filter($data);

        $platform_id = Platform::query()->where('name', $platform)->value('id');

        $weight = count($data);
        foreach ($data as $k => $item) {
            $weight --;
            $data[$k]['platform_id'] = $platform_id;
            $data[$k]['weight'] = $weight;
        }

        return $data;
    }

    /**
     * 去重
     * User: surest
     * Date: 2019/12/24
     */
    public function filter(array $data) :array
    {
        # 去重
        $redis = getRedis();
        $data = array_filter($data, function($item) use ($redis){
            $url = Arr::get($item, 'url');
            $md5_url = md5($url);
            $is = $redis->sismember($this->key, $md5_url);
            return !$is;
        });

        return $data;
    }

    /**
     * 保存到redis中防止重复写入
     * User: surest
     * Date: 2019/12/24
     */
    public function save(array $data)
    {
        $redis = getRedis();
        $urls = collect($data)->pluck('url')->toArray();
        foreach ($urls as $url) {
            $url = md5($url);
            $redis->sadd($this->key, [$url]);
            $redis->persist($this->key);
        }
    }

    /**
     * 保存标签
     * User: surest
     * Date: 2019/12/24
     * @param array $data
     * @param $tag
     */
    public function saveTag(array $data, $tags)
    {
        $urls = collect($data)->pluck('url');
        $ids = Article::query()->whereIn('url', $urls)->get(['id'])->pluck('id')->toArray();

        $tagRelations = [];

        foreach ($ids as $id) {
            foreach ($tags as $tag) {
                $item = [
                    'article_id' => $id,
                    'tag_id' => $tag
                ];
                array_push($tagRelations, $item);
            }
        }

        TagRelation::query()->insert($tagRelations);
    }
}
